using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using GalaSoft.MvvmLight.Threading;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;
using Windows.ApplicationModel.DataTransfer;
using Windows.UI.Notifications;
using Newtonsoft.Json;
using OurDailyBread.Model;
using OurDailyBread.ViewModel;
using System.Collections.ObjectModel;
using System.Collections;
using Windows.UI.ApplicationSettings;
using Windows.UI.Popups;

namespace OurDailyBread
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    sealed partial class App : Application
    {
        public AppContext Context { get; set; }
        public DataTransferManager dtm { get; set; }


        // This is the container that will hold our custom content.
        private Popup settingsPopup;

        // Used to determine the correct height to ensure our custom UI fills the screen.
        Rect windowBounds;

        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            InitializeComponent();
            Suspending += OnSuspending;
            Windows.Storage.ApplicationData.Current.DataChanged +=
                new TypedEventHandler<Windows.Storage.ApplicationData, object>(RoamingDataChangeHandler);

        }

        private void OnWindowSizeChanged(object sender, Windows.UI.Core.WindowSizeChangedEventArgs e)
        {
            windowBounds = Window.Current.Bounds;
        }

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {


            TileUpdateManager.CreateTileUpdaterForApplication().EnableNotificationQueue(true);

            dtm = DataTransferManager.GetForCurrentView();
            dtm.DataRequested += ShareTextHandler;
            SettingsPane.GetForCurrentView().CommandsRequested += onCommandsRequested;

            windowBounds = Window.Current.Bounds;

            // Added to listen for events when the window size is updated.
            Window.Current.SizeChanged += OnWindowSizeChanged;

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                    Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
                    string breadContext = (string)localSettings.Values["BreadContext"];

                    if (breadContext == null)
                    {
                        // No data
                        Context = new AppContext(System.DateTime.Today);
                    }
                    else
                    {
                        Context = JsonConvert.DeserializeObject<AppContext>(breadContext);

                    }

                }
                else
                {
                    // newly launched 
                    Context = new AppContext(System.DateTime.Today);
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(typeof(MainPage), args.Arguments))
                {
                    throw new Exception("Failed to create initial page");
                }
            }
            // Ensure the current window is active
            Window.Current.Activate();

            DispatcherHelper.Initialize();
        }

        private void onCommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
        {
            UICommandInvokedHandler handler = new UICommandInvokedHandler(onSettingsCommand);

            SettingsCommand generalCommand = new SettingsCommand("AboutId", "About", handler);
            args.Request.ApplicationCommands.Add(generalCommand);
        }

        private void onSettingsCommand(IUICommand command)
        {

        
            // Desired width for the settings UI. UI guidelines specify this should be 346 or 646 depending on your needs.
             double settingsWidth = 346;


            // Create a Popup window which will contain our flyout.
            settingsPopup = new Popup();
            settingsPopup.Closed += OnPopupClosed;
            Window.Current.Activated += OnWindowActivated;
            settingsPopup.IsLightDismissEnabled = true;
            settingsPopup.Width = settingsWidth;
            settingsPopup.Height = windowBounds.Height;

            // Add the proper animation for the panel.
            settingsPopup.ChildTransitions = new TransitionCollection();
            settingsPopup.ChildTransitions.Add(new PaneThemeTransition()
            {
                Edge = (SettingsPane.Edge == SettingsEdgeLocation.Right) ?
                       EdgeTransitionLocation.Right :
                       EdgeTransitionLocation.Left
            });

            // Create a SettingsFlyout the same dimenssions as the Popup.
            AboutSettingFlyout mypane = new AboutSettingFlyout();
            mypane.Width = settingsWidth;
            mypane.Height = windowBounds.Height;

            // Place the SettingsFlyout inside our Popup window.
            settingsPopup.Child = mypane;

            // Let's define the location of our Popup.
            settingsPopup.SetValue(Canvas.LeftProperty, SettingsPane.Edge == SettingsEdgeLocation.Right ? (windowBounds.Width - settingsWidth) : 0);
            settingsPopup.SetValue(Canvas.TopProperty, 0);
            settingsPopup.IsOpen = true;
        }

        private void OnWindowActivated(object sender, Windows.UI.Core.WindowActivatedEventArgs e)
        {
            if (e.WindowActivationState == Windows.UI.Core.CoreWindowActivationState.Deactivated)
            {
                settingsPopup.IsOpen = false;
            }
        }

        private void OnPopupClosed(object sender, object e)
        {
            Window.Current.Activated -= OnWindowActivated;
        }

        private void ShareTextHandler(DataTransferManager sender, DataRequestedEventArgs args)
        {
            DataRequest request = args.Request;
            request.Data.Properties.Title = Context.BreadTitle;
            request.Data.Properties.Description = Context.ShortVerse;
            request.Data.SetText("Daily Bread\n" + Context.BreadContent);
            request.Data.SetUri(new Uri(Context.BreadUrl));
        }

        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();

            // Save application state and stop any background activity
            Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

            string breadContext = JsonConvert.SerializeObject(Context);
            localSettings.Values["BreadContext"] = breadContext;

            deferral.Complete();
        }

        private void RoamingDataChangeHandler(Windows.Storage.ApplicationData appData, object o)
        {
            // TODO: Refresh your data
            Windows.Storage.ApplicationDataContainer roamingSettings = appData.RoamingSettings;
            string myLikeListString = (string)roamingSettings.Values["MyLikes"];
            if (myLikeListString != null)
            {
                Context.mvw.MyLikeList = JsonConvert.DeserializeObject<ObservableCollection<RoamingLikes>>((string)myLikeListString);
            }
            else
            {
                Context.mvw.MyLikeList = null;
            }

        }

 
    }
}
